from asyncio import async
import logging
import logging.config
import log
import asyncio
import tornado.ioloop
import tornado.web
import time
from datetime import datetime



class DateHandler(tornado.web.RequestHandler):
    def get(self):
        _time = datetime.now()
        _datetime = _time.strftime('%Y/%m/%d %H:%M:%S')
        time.sleep(2)
        self.write(_datetime)



class AsyncDateHandler(tornado.web.RequestHandler):
    async def get(self):
        _time=datetime.now()
        _datetime= _time.strftime('%Y/%m/%d %H:%M:%S')
        await asyncio.sleep(2)
        self.write(_datetime)

# 1. 利用父类方法，统计每一次请求的时间和路径，保持到文件中: log.log

# logging.config.dictConfig(config)
# logger=logging.getLogger(__name__)

class LogHandler(tornado.web.RequestHandler):
    def initialize(self):
        logging.info(('请求内容：',self.request),)
    def get(self, *args, **kwargs):
        self.write("11")




# 2. 配置动态路由，将url 中的内容，显示到网页中
class UrlHandler(tornado.web.RequestHandler):
    def get(self,  *args, **kwargs):
        self.write(*args)


# 3. 设置一个重定向，如果动态路由捕获的url 中有“error"，重定向到m.baidu.com
class RedirectHandler(tornado.web.RequestHandler):
    def get(self,id="0",*args, **kwargs):
        if 'error' in id:
            self.redirect('http://m.baidu.com')
        else:
            self.write(id)





url=[('/',DateHandler),
     ('/async',AsyncDateHandler),
     ('/log',LogHandler),
     (r'/url/(.+)',UrlHandler),
     (r'/redirect/(\S+)',RedirectHandler),]

app=tornado.web.Application(url)
app.listen(8001)
loop=tornado.ioloop.IOLoop.current()
print(111)
loop.start()